from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from oauth.exceptions import QQAPIError
from oauth.models import OAuthQQUser
from oauth.serializers import OAuthQQUserSerializer
from oauth.utils import OAuthQQ


# Create your views here.
# GET /oauth/qq/user/?code=<code>
class QQAuthUserView(GenericAPIView):
    serializer_class = OAuthQQUserSerializer

    def post(self,request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(serializer.data,status=status.HTTP_201_CREATED)

    def get(self, request):
        """
        获取QQ登录用户的openid并处理
        1.获取code并校验(code必传)
        2.获取QQ登录用户的openid
            2.1 通过code请求QQ服务器获取access_token
            2.2 通过access_token请求QQ服务器获取openid
        3.根据openid判断是否绑定过本网站的用户
            3.1如果已绑定，直接生成jwt token并返回
            3.2如果未绑定，将openid加密并返回
        """
        code = request.query_params.get('code')

        # code必传
        if code is None:
            return Response({'message': '缺少code参数'}, status=status.HTTP_400_BAD_REQUEST)

        oauth = OAuthQQ()

        try:
            # 通过code请求QQ服务器获取access_token
            access_token = oauth.get_access_token(code)
            # 通过access_token请求QQ服务器获取openid
            openid = oauth.get_openid(access_token)
        except QQAPIError:
            return Response({'message': 'QQ登录异常'})

        # 3.根据openid判断用户是否登录过本网站
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 用户未绑定，将openid加密并返回
            secret_openid = OAuthQQ.generate_save_user_token(openid)
            return Response({'access_token': secret_openid})
        else:
            # 用户已绑定，直接生成jwt token并返回
            user = qq_user.user
            # 由服务器生成一个jwt token保存用户身份信息
            from rest_framework_jwt.settings import api_settings

            # 生成payload的方法
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            # 生成jwt token的方法
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 生成payload
            payload = jwt_payload_handler(user)
            # 生成jwt token
            token = jwt_encode_handler(payload)

            # 返回应答
            res_data = {
                'user_id': user.id,
                'user_name': user.username,
                'token': token
            }
            return Response(res_data)


# GET /oauth/authorization/?next=<登录之后访问页面>
class QQAuthURLView(APIView):
    def get(self, request):
        """
        获取QQ登录网址：
        1.获取next
        2.组织QQ登录网址和参数
        3.返回QQ登录网址
        """
        # 1.获取next
        next = request.query_params.get('next', '/')

        # 2.组织QQ登录网址和参数
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_login_url()

        # 3.返回QQ登录网址
        return Response({'login_url': login_url})